﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using professional;
using sqlsearcher.Models;
using sqlsearcher.Services;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static sqlsearcher.HttpClient;

namespace sqlsearcher.Forms
{
    public partial class MenuFm : Form
    {
        public string SqlServerAddColumnDesc = "\r\n   EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'$columnDesc' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'$tableName', @level2type=N'COLUMN',@level2name=N'$columnName' \r\nGO";
        public string MySQLAddColumnDesc = "ALTER TABLE $tableName MODIFY COLUMN $columnName $columnDataType COMMENT '$columnDesc';";
        private List<TreeMapInfo> data;
        private static List<HttpEntity> https = new List<HttpEntity>();
        private static CNSqlSearch sqlCnSearch;
        public MenuFm()
        {
            InitializeComponent();
            this.Init();
        }

        private void Init()
        {
            this.tsRunQuery.Click += new System.EventHandler(this.btnRunSqlLoading_Click);
            this.tsRunQuery.Click += new System.EventHandler(this.btnRunSql_Click);
            this.Load += Menu_Load;
            sqlCnSearch = new CNSqlSearch();
            this.tabSQLQuery.Dock = DockStyle.Fill;
            this.txtSql.Dock = DockStyle.Fill;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }


        private void Menu_Load(object sender, System.EventArgs e)
        {
            cbxHttpMethod.SelectedIndex = 0;
            this.lbxHttpHistory.Visible = false;
            AppConst.InitHelpers();
            InitActions();

            ReLoad();

        }
        public void InitActions()
        {

            AppConst.InitActions<AppEnum.Computer_1>((int)AppEnum.Computer_1.systemInfos, exToolsBySystem_Click);
            AppConst.InitActions<AppEnum.Computer_1>((int)AppEnum.Computer_1.services, exToolsByWinService_Click);
            AppConst.InitActions<AppEnum.Computer_1>((int)AppEnum.Computer_1.regedt32, toolStripButton3_Click);
            AppConst.InitActions<AppEnum.Computer_1>((int)AppEnum.Computer_1.mstsc, toolStripButton2_Click);
            AppConst.InitActions<AppEnum.Computer_1>((int)AppEnum.Computer_1.systemConfig, exToolsSysInfo_Click);


            AppConst.InitActions<AppEnum.ZhengZe_302>((int)AppEnum.ZhengZe_302.ZNum, btnRegNum_Click);
            AppConst.InitActions<AppEnum.ZhengZe_302>((int)AppEnum.ZhengZe_302.NZnum, btnRegUn0Number_Click);
            AppConst.InitActions<AppEnum.ZhengZe_302>((int)AppEnum.ZhengZe_302.DoubleNum, btnRegTwoPrice_Click);
            AppConst.InitActions<AppEnum.ZhengZe_302>((int)AppEnum.ZhengZe_302.Chinese, btnRegChinese_Click);
            AppConst.InitActions<AppEnum.ZhengZe_302>((int)AppEnum.ZhengZe_302.EnNum, btnRegEnNum_Click);
            AppConst.InitActions<AppEnum.ZhengZe_302>((int)AppEnum.ZhengZe_302.Email, btnRegEmail_Click);
            AppConst.InitActions<AppEnum.ZhengZe_302>((int)AppEnum.ZhengZe_302.DomainName, btnRegDomain_Click);
            AppConst.InitActions<AppEnum.ZhengZe_302>((int)AppEnum.ZhengZe_302.InternetURL, btnRegInter_Click);
            AppConst.InitActions<AppEnum.ZhengZe_302>((int)AppEnum.ZhengZe_302.Phone, btnRegMobilePhone_Click);
            AppConst.InitActions<AppEnum.ZhengZe_302>((int)AppEnum.ZhengZe_302.CellNumber, btnRegPhone_Click);
            AppConst.InitActions<AppEnum.ZhengZe_302>((int)AppEnum.ZhengZe_302.IDCard, btnIDCard_Click);
            AppConst.InitActions<AppEnum.ZhengZe_302>((int)AppEnum.ZhengZe_302.SafePwd, btnRegPwd_Click);
            AppConst.InitActions<AppEnum.ZhengZe_302>((int)AppEnum.ZhengZe_302.Account, toolStripLabel12_Click);
            AppConst.InitActions<AppEnum.ZhengZe_302>((int)AppEnum.ZhengZe_302.Date, btnRegDate_Click);
            AppConst.InitActions<AppEnum.ZhengZe_302>((int)AppEnum.ZhengZe_302.QQ, btnRegQQ_Click);
            AppConst.InitActions<AppEnum.ZhengZe_302>((int)AppEnum.ZhengZe_302.ECode, btnRegEmailCode_Click);
            AppConst.InitActions<AppEnum.ZhengZe_302>((int)AppEnum.ZhengZe_302.IP, btnRegIP_Click);
            AppConst.InitActions<AppEnum.ZhengZe_302>((int)AppEnum.ZhengZe_302.Layui, toolStripLabel2_Click);
            AppConst.InitActions<AppEnum.ZhengZe_302>((int)AppEnum.ZhengZe_302.Cxp, toolStripLabel3_Click);
            AppConst.InitActions<AppEnum.ZhengZe_302>((int)AppEnum.ZhengZe_302.Js, toolStripLabel4_Click);
            AppConst.InitActions<AppEnum.ZhengZe_302>((int)AppEnum.ZhengZe_302.All, btnRegAll_Click);

        }

        public void ReLoad()
        {
            try
            {
                var server = SearchManager.Server == "." ? "(Local)" : SearchManager.Server;
                this.tvView.Nodes.Clear();
                this.tvView.Nodes.Add(server);
                this.Text = server;
                var dbs = TFac<SearchManager>.Instance.GetDataBases();
                if (dbs.Item1)
                {
                    data = dbs.Item2;
                    this.tvView.Nodes[0].ImageIndex = (int)ImgLevel.Server;
                    this.tvView.Nodes[0].SelectedImageIndex = (int)ImgLevel.Server;
                    TreeNode(dbs.Item2, this.tvView.Nodes[0]);

                    if (dbs.Item1)
                    {
                        cbDb.DataSource = dbs.Item2;
                        cbDb.DisplayMember = "Node";
                        cbDb.ValueMember = "Node";

                        cbx_Desc.DataSource = dbs.Item2;
                        cbx_Desc.DisplayMember = "Node";
                        cbx_Desc.ValueMember = "Node";
                        cbx_Desc.SelectedIndex = 0;

                        cbx_DBs.DataSource = dbs.Item2;
                        cbx_DBs.DisplayMember = "Node";
                        cbx_DBs.ValueMember = "Node";
                        cbx_DBs.SelectedIndex = 0;
                    }
                }


                var dics = TFac<JsonManager>.Instance.GetModelTemplate();
                if (dics != null && dics.Count > 0)
                {

                    cbx_Models.Items.Clear();
                    foreach (var item in dics)
                    {
                        cbx_Models.Items.Add(item.Key);

                    }
                    cbx_Models.SelectedIndex = 0;

                    txtContent.Text = dics.First().Value;
                    labModelMsg.Text = "加载" + dics.First().Key + "成功!";

                }


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "消息提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        public void TreeNode(List<TreeMapInfo> maps, TreeNode tn)
        {
            try
            {
                var tmps = new List<TreeMapInfo>();
                if (tn.Level == 0)
                {
                    tmps = maps;
                }
                else
                {
                    tmps = maps.Where(m => m.ParentNode == tn.Text).ToList();
                }

                foreach (var item in tmps)
                {
                    TreeNode tc = new System.Windows.Forms.TreeNode();
                    tc.Text = item.Node;
                    tc.ImageIndex = tn.ImageIndex + 1;
                    tc.SelectedImageIndex = tn.ImageIndex + 1;
                    if (item.IsKey == ((int)YNStatus.Yes).ToString())
                    {
                        tc.ImageIndex = (int)ImgLevel.Key;
                        tc.SelectedImageIndex = (int)ImgLevel.Key;
                    }
                    tn.Nodes.Add(tc);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "消息提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void tvView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                if (tvView.SelectedNode.Level == 1)
                {
                    var value = tvView.SelectedNode.Text;
                    if (tvView.SelectedNode.Nodes.Count == 0)
                    {
                        var tbs = TFac<SearchManager>.Instance.GetTables(value);

                        if (tbs.Item1)
                        {
                            data.Find(m => m.Node == value).Items = tbs.Item2;
                            TreeNode(tbs.Item2, tvView.SelectedNode);

                            sqlCnSearch.CurrentDB = value;
                            Task.Factory.StartNew(() =>
                            {
                                sqlCnSearch.Fill(TFac<SearchManager>.Instance.GetDataTableBySql(sqlCnSearch.CurrentDB, sqlCnSearch.GetTableDescSQL()));
                            });
                        }
                    }
                }
                else if (tvView.SelectedNode.Level == 2)
                {
                    var value = tvView.SelectedNode.Text;
                    if (tvView.SelectedNode.Nodes.Count == 0)
                    {
                        var cns = TFac<SearchManager>.Instance.GetColumns(tvView.SelectedNode.Parent.Text, value);

                        if (cns.Item1)
                        {
                            data.Find(m => m.Node == tvView.SelectedNode.Parent.Text).Items.Find(m => m.Node == value).Items = cns.Item2;
                            TreeNode(cns.Item2, tvView.SelectedNode);
                        }
                    }
                    var viewData = TFac<SearchManager>.Instance.GetDetails(tvView.SelectedNode.Parent.Text, value);
                    if (viewData.Item1 > 0)
                    {
                        this.gridView.DataSource = viewData.Item2;
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "消息提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (data != null && data.Count > 0)
                {
                    if (!string.IsNullOrEmpty(txtSearch.Text))
                    {
                        //  保存树
                        var query = txtSearch.Text.Trim().ToLower();

                        TreeNode rootNode = new TreeNode();
                        rootNode.Text = "服务器";
                        rootNode.ImageIndex = (int)ImgLevel.Server;
                        rootNode.SelectedImageIndex = (int)ImgLevel.Server;
                        this.tvView.Nodes.Clear();
                        foreach (var item in data)
                        {
                            var isAdd = false;
                            if (item.Node.ToLower().IndexOf(query.ToLower()) != -1)
                            {
                                isAdd = true;
                            }
                            TreeNode dbNode = new TreeNode();
                            dbNode.Text = item.Node;
                            dbNode.ImageIndex = rootNode.ImageIndex + 1;
                            dbNode.SelectedImageIndex = rootNode.ImageIndex + 1;
                            if (item.Items != null)
                            {
                                foreach (var tc in item.Items)
                                {
                                    var isAddTc = false;
                                    if (tc.Node.ToLower().IndexOf(query.ToLower()) != -1)
                                    {
                                        isAdd = true;
                                        isAddTc = true;
                                    }
                                    TreeNode tcNode = new TreeNode();
                                    tcNode.Text = tc.Node;
                                    tcNode.ImageIndex = rootNode.ImageIndex + 2;
                                    tcNode.SelectedImageIndex = rootNode.ImageIndex + 2;
                                    if (tc.Items != null)
                                    {
                                        foreach (var tdc in tc.Items)
                                        {
                                            var isAddTDc = false;
                                            if (tdc.Node.ToLower().IndexOf(query.ToLower()) != -1)
                                            {
                                                isAdd = true;
                                                isAddTc = true;
                                                isAddTDc = true;
                                            }
                                            TreeNode tdcNode = new TreeNode();
                                            tdcNode.Text = tdc.Node;
                                            tdcNode.ImageIndex = rootNode.ImageIndex + 2;
                                            tdcNode.SelectedImageIndex = rootNode.ImageIndex + 2;
                                            if (tdc.IsKey == ((int)YNStatus.Yes).ToString())
                                            {
                                                tdcNode.ImageIndex = (int)ImgLevel.Key;
                                                tdcNode.SelectedImageIndex = (int)ImgLevel.Key;
                                            }
                                            if (isAddTDc)
                                            {
                                                tcNode.Nodes.Add(tdcNode);
                                            }
                                        }
                                    }
                                    if (isAddTc)
                                    {
                                        dbNode.Nodes.Add(tcNode);
                                    }
                                }
                            }
                            if (isAdd)
                            {
                                rootNode.Nodes.Add(dbNode);
                            }
                        }

                        this.tvView.Nodes.Add(rootNode);
                        this.tvView.ExpandAll();
                    }
                    else
                    {
                        TreeNode rootNode = new TreeNode();
                        rootNode.Text = "服务器";
                        rootNode.ImageIndex = (int)ImgLevel.Server;
                        rootNode.SelectedImageIndex = (int)ImgLevel.Server;
                        this.tvView.Nodes.Clear();

                        foreach (var item in data)
                        {
                            var isAdd = true;
                            TreeNode dbNode = new TreeNode();
                            dbNode.Text = item.Node;
                            dbNode.ImageIndex = rootNode.ImageIndex + 1;
                            dbNode.SelectedImageIndex = rootNode.ImageIndex + 1;
                            if (item.Items != null)
                            {
                                foreach (var tc in item.Items)
                                {
                                    var isAddTc = true;
                                    isAdd = true;
                                    isAddTc = true;
                                    TreeNode tcNode = new TreeNode();
                                    tcNode.Text = tc.Node;
                                    tcNode.ImageIndex = rootNode.ImageIndex + 2;
                                    tcNode.SelectedImageIndex = rootNode.ImageIndex + 2;
                                    if (tc.Items != null)
                                    {
                                        foreach (var tdc in tc.Items)
                                        {
                                            var isAddTDc = true;
                                            isAdd = true;
                                            isAddTc = true;
                                            isAddTDc = true;
                                            TreeNode tdcNode = new TreeNode();
                                            tdcNode.Text = tdc.Node;
                                            tdcNode.ImageIndex = rootNode.ImageIndex + 1;
                                            tdcNode.SelectedImageIndex = rootNode.ImageIndex + 1;
                                            if (tdc.IsKey == ((int)YNStatus.Yes).ToString())
                                            {
                                                tdcNode.ImageIndex = (int)ImgLevel.Key;
                                                tdcNode.SelectedImageIndex = (int)ImgLevel.Key;
                                            }
                                            if (isAddTDc)
                                            {
                                                tcNode.Nodes.Add(tdcNode);
                                            }
                                        }
                                    }
                                    if (isAddTc)
                                    {
                                        dbNode.Nodes.Add(tcNode);
                                    }
                                }
                            }
                            if (isAdd)
                            {
                                rootNode.Nodes.Add(dbNode);
                            }
                        }

                        this.tvView.Nodes.Add(rootNode);
                        this.tvView.CollapseAll();
                        this.tvView.Nodes[0].Expand();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "消息提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

        }



        public enum ImgLevel
        {
            Server = 0,
            Db = 1,
            Tb = 2,
            Tc = 3,
            Key = 4,
        }

        public enum YNStatus
        {
            No = 0,
            Yes = 1
        }

        private void btnTcRemark_Click(object sender, EventArgs e)
        {

        }

        private void btnTm_Click(object sender, EventArgs e)
        {

        }

        private DataGridView getNewGridView()
        {
            var gridView = new DataGridView();
            gridView.BackgroundColor = System.Drawing.Color.White;
            gridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            gridView.Dock = System.Windows.Forms.DockStyle.Fill;
            gridView.Location = new System.Drawing.Point(3, 3);
            gridView.Margin = new System.Windows.Forms.Padding(4);
            gridView.Name = "dataGridView1";
            gridView.RowHeadersWidth = 51;
            gridView.RowTemplate.Height = 23;
            gridView.Size = new System.Drawing.Size(1266, 94);
            gridView.TabIndex = 0;
            gridView.DataError += GridView_DataError;
            return gridView;
        }

        private void GridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void btnRunSql_Click(object sender, EventArgs e)
        {
            if (tabSQLQuery.SelectedTab == null)
                return;
            foreach (var item in tabSQLQuery.SelectedTab.Controls)
            {
                if (item is RichTextBox)
                {
                    buildRun(tabSQLQuery.SelectedTab, item as RichTextBox);
                }
            }
        }

        private void buildRun(TabPage queryTab, RichTextBox rtxt)
        {
            try
            {
                string execSQL = rtxt.Text;
                if (string.IsNullOrWhiteSpace(rtxt.SelectedText) && string.IsNullOrWhiteSpace(rtxt.Text))
                    return;

                if (cbDb.SelectedIndex == -1)
                {
                    rtxt.Text.Insert(0, "需要指定数据库");
                    return;
                }

                if (!string.IsNullOrWhiteSpace(rtxt.SelectedText))
                    execSQL = rtxt.SelectedText;

                var ds = TFac<SearchManager>.Instance.GetDataSets(execSQL, cbDb.Text);
                var dataCount = 0;
                for (int i = 0; i < ds.Tables.Count; i++)
                {
                    var tabPage = new TabPage();
                    var isAddTabPage = true;
                    foreach (TabPage item in tabSqlResult.TabPages)
                    {
                        if (item.Text == queryTab.Text + "的结果"+(i+1))
                        {
                            tabPage = item;
                            tabSqlResult.SelectTab(item);
                            isAddTabPage = false;
                        }

                    }
                    tabPage.Text = queryTab.Text + "的结果"+(i+1);
                    tabPage.Controls.Clear();

                    var gridView = getNewGridView();
                    gridView.DataSource = ds.Tables[i];

                    tabPage.Controls.Add(gridView);
                    if (isAddTabPage)
                    {
                        tabSqlResult.TabPages.Add(tabPage);
                        tabSqlResult.SelectTab(tabPage);

                    }
                    dataCount += ds.Tables[i].Rows.Count;
                }

                if (dataCount == 0)
                {
                    txtSqlResult.Text = "没有查到任何数据";
                }
                else
                {
                    txtSqlResult.Text = $"一共查到：{dataCount}行数据";
                }

                UpdateQuerySQLStyle(null, null);
            }
            catch (Exception ex)
            {
                txtSqlResult.Text = ex.Message;
            }
            SQLLoading(false);
        }




        private void 运行ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            try
            {

                var dbs = TFac<SearchManager>.Instance.GetDataBases();
                if (dbs.Item1)
                {
                    cbDb.DataSource = dbs.Item2;
                    cbDb.DisplayMember = "Node";
                    cbDb.ValueMember = "Node";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "消息提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void Menu_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtFileName.Text.Trim()) || string.IsNullOrEmpty(txtContent.Text))
                {
                    labModelMsg.Text = "没有查到任何数据";
                    return;
                }
                TFac<JsonManager>.Instance.InsertModelTemplate(txtFileName.Text, txtContent.Text);
                labModelMsg.Text = "添加" + txtFileName.Text + "成功!";

                var dics = TFac<JsonManager>.Instance.GetModelTemplate();
                if (dics != null && dics.Count > 0)
                {
                    cbx_Models.Items.Clear();
                    foreach (var item in dics)
                    {
                        cbx_Models.Items.Add(item.Key);
                    }
                    cbx_Models.SelectedIndex = 0;
                    txtContent.Text = dics.First().Value;
                    labModelMsg.Text = "加载" + dics.First().Key + "成功!";
                }
                labModelMsg.Text = "添加" + txtFileName.Text + "成功!";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "消息提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (cbx_Models.SelectedIndex != -1)
                {
                    var dics = TFac<JsonManager>.Instance.GetModelTemplate();
                    if (dics != null && dics.Count > 0)
                    {
                        txtContent.Text = dics[cbx_Models.Text];
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "消息提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            try
            {
                if (cbx_Models.SelectedIndex != -1)
                {
                    TFac<JsonManager>.Instance.RemoveModelTemplate(cbx_Models.Text);

                    var dics = TFac<JsonManager>.Instance.GetModelTemplate();
                    if (dics != null && dics.Count > 0)
                    {
                        cbx_Models.Items.Clear();
                        foreach (var item in dics)
                        {
                            cbx_Models.Items.Add(item.Key);
                        }
                        cbx_Models.SelectedIndex = 0;
                        txtContent.Text = dics.First().Value;
                        labModelMsg.Text = "加载" + dics.First().Key + "成功!";
                    }
                    labModelMsg.Text = "作废" + txtFileName.Text + "成功!";
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "消息提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (cbx_Models.SelectedIndex != -1)
                {
                    TFac<JsonManager>.Instance.UpModelTemplate(cbx_Models.Text, txtContent.Text);
                    labModelMsg.Text = "修改" + txtFileName.Text + "成功!";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "消息提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void txtDescSearch_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (cbx_Desc.SelectedIndex == -1)
                {
                    return;
                }
                var tbs = TFac<SearchManager>.Instance.GetTables(cbx_Desc.Text);
                var isAllMatch = false;
                if (tbs.Item1)
                {
                    lbxDesc.Items.Clear();
                    foreach (var item in tbs.Item2.Where(m => m.Node.ToLower().IndexOf(txtDescSearch.Text.ToLower()) != -1).ToList())
                    {
                        if (item.Node.ToLower() == txtDescSearch.Text)
                        {
                            isAllMatch = true;
                        }
                        lbxDesc.Items.Add(item.Node);
                    }
                }
                if (isAllMatch)
                {
                    var viewData = TFac<SearchManager>.Instance.GetDescs(cbx_Desc.Text, txtDescSearch.Text);
                    gridDesc.DataSource = viewData.Item2;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "消息提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void lbxDesc_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (lbxDesc.SelectedIndex != -1)
                {
                    lbxDesc.Visible = false;
                    txtDescSearch.Text = lbxDesc.Text;

                    var viewData = TFac<SearchManager>.Instance.GetDescs(cbx_Desc.Text, txtDescSearch.Text);
                    gridDesc.DataSource = viewData.Item2;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "消息提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void txtDescSearch_MouseDown(object sender, MouseEventArgs e)
        {
            lbxDesc.Visible = true;
        }

        private void txtSearchTableByCode_MouseDown(object sender, MouseEventArgs e)
        {
            lbxSearchTable_Code.Visible = true;
        }

        private void txtSearchTableByCode_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (cbx_DBs.SelectedIndex == -1)
                {
                    return;
                }
                var tbs = TFac<SearchManager>.Instance.GetTables(cbx_DBs.Text);
                if (tbs.Item1)
                {
                    lbxSearchTable_Code.Items.Clear();
                    foreach (var item in tbs.Item2.Where(m => m.Node.ToLower().IndexOf(txtSearchTableByCode.Text.ToLower()) != -1).ToList())
                    {

                        lbxSearchTable_Code.Items.Add(item.Node);
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "消息提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void lbxSearchTable_Code_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (lbxSearchTable_Code.SelectedIndex != -1)
                {
                    lbxSearchTable_Code.Visible = false;
                    txtSearchTableByCode.Text = lbxSearchTable_Code.Text;

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "消息提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnCreateCode_Click(object sender, EventArgs e)
        {
            try
            {
                if (cbx_DBs.SelectedIndex != -1)
                {
                    var dics = TFac<JsonManager>.Instance.GetModelTemplate();
                    if (dics != null && dics.Count > 0)
                    {
                        var template = dics[cbx_Models.Text];
                        txtContent.Text = TFac<SearchManager>.Instance.Create(template, txtSearchTableByCode.Text, cbx_DBs.Text);
                        if (!this.cbxIsNull.Checked)
                        {
                            txtContent.Text = txtContent.Text.Replace("?", "");
                            Clipboard.SetDataObject(txtContent.Text);
                            labModelMsg.Text = "代码已复制!";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "消息提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void gridDesc_MouseLeave(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtDescSearch.Text))
                return;

            var tb = txtDescSearch.Text;
            string template = SqlServerAddColumnDesc;
            if (SearchManager.LoginDBType == (int)AppEnum.DBType.MySQL)
            {
                template = MySQLAddColumnDesc;
            }

            StringBuilder sb = new StringBuilder();

            foreach (DataGridViewRow item in this.gridDesc.Rows)
            {
                if (item.Cells["DcName"].Value == null) continue;
                if (item.Cells["Desc"].Value == null) continue;
                if (!string.IsNullOrEmpty(item.Cells["Desc2Hide"].Value.TryString())) continue;
                if (!string.IsNullOrEmpty(item.Cells["Desc"].Value.ToString()))
                {
                    if (SearchManager.LoginDBType == (int)AppEnum.DBType.SQLServer)
                    {
                        sb.AppendLine(template.Format(new
                        {
                            columnDesc = item.Cells["Desc"].Value.ToString(),
                            tableName = tb,
                            columnName = item.Cells["DcName"].Value.ToString()
                        }));
                    }
                    else if (SearchManager.LoginDBType == (int)AppEnum.DBType.MySQL)
                    {
                        sb.AppendLine(template.Format(new
                        {
                            columnDesc = item.Cells["Desc"].Value.ToString(),
                            tableName = tb,
                            columnName = item.Cells["DcName"].Value.ToString(),
                            columnDataType = item.Cells["cType"].Value.ToString()
                        }));
                    }

                }

            }

            this.txtDesc.Text = sb.ToString();
            if (sb.Length == 0)
            {
                this.txtDesc.Text = "没有新生成的描述脚本";
            }
        }

        private void btnReLoadDescSQL_Click(object sender, EventArgs e)
        {
            gridDesc_MouseLeave(null, null);
        }

        private void btnSubDesc_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(txtDesc.Text))
            {
                int res = TFac<SearchManager>.Instance.AddDescription(cbx_Desc.Text, txtDesc.Text);
                txtDesc.Text = string.Format("{0}行受影响", res);
            }
        }

        private void 刷新F5ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ReLoad();
        }

        private void toolStripLabel12_Click(object sender, EventArgs e)
        {

        }

        private void btnRegAll_Click(object sender, EventArgs e)
        {
            //this.txtRegex.Text = AppRegCost.AllReg;
            this.setRegText(AppRegCost.AllReg);
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void setRegText(string str)
        {
            //this.txtRegex.Text = str;
            //this.txtRegex.SelectAll();
            //this.txtRegex.SelectionBackColor = Color.Green;
            //this.txtRegex.SelectionColor = Color.White;
            //Clipboard.SetDataObject(txtRegex.Text);

            TFac<TxtFrm>.Instance.txtMsg.Text = str;
            TFac<TxtFrm>.Instance.StartPosition = FormStartPosition.CenterScreen;
            TFac<TxtFrm>.Instance.ShowDialog();
        }
        private void btnRegNum_Click(object sender, EventArgs e)
        {
            setRegText(AppRegCost.ZZSReg);
        }

        private void btnRegTwoPrice_Click(object sender, EventArgs e)
        {
            setRegText(AppRegCost.TwoNum);
        }

        private void btnRegUn0Number_Click(object sender, EventArgs e)
        {
            setRegText(AppRegCost.Not0);
        }

        private void btnRegChinese_Click(object sender, EventArgs e)
        {
            setRegText(AppRegCost.CN);
        }

        private void btnRegEnNum_Click(object sender, EventArgs e)
        {
            setRegText(AppRegCost.ENNum);
        }

        private void btnRegEmail_Click(object sender, EventArgs e)
        {
            setRegText(AppRegCost.Email);
        }

        private void btnRegDomain_Click(object sender, EventArgs e)
        {
            setRegText(AppRegCost.RegDomain);
        }

        private void btnRegInter_Click(object sender, EventArgs e)
        {
            setRegText(AppRegCost.RegInter);
        }

        private void btnRegMobilePhone_Click(object sender, EventArgs e)
        {
            setRegText(AppRegCost.RegMobilePhone);
        }

        private void btnRegPhone_Click(object sender, EventArgs e)
        {
            setRegText(AppRegCost.RegPhone);
        }

        private void btnIDCard_Click(object sender, EventArgs e)
        {
            setRegText(AppRegCost.IDCard);
        }

        private void btnRegPwd_Click(object sender, EventArgs e)
        {
            setRegText(AppRegCost.RegPwd);
        }

        private void btnRegDate_Click(object sender, EventArgs e)
        {
            setRegText(AppRegCost.RegDate);
        }

        private void btnRegQQ_Click(object sender, EventArgs e)
        {
            setRegText(AppRegCost.RegQQ);
        }

        private void btnRegEmailCode_Click(object sender, EventArgs e)
        {
            setRegText(AppRegCost.RegEmailCode);
        }

        private void btnRegIP_Click(object sender, EventArgs e)
        {
            setRegText(AppRegCost.RegIP);
        }

        private void toolStripLabel2_Click(object sender, EventArgs e)
        {
            setRegText(AppRegCost.RegLayui);
        }

        private void toolStripLabel3_Click(object sender, EventArgs e)
        {
            setRegText(AppRegCost.RegNet);
        }

        private void toolStripLabel4_Click(object sender, EventArgs e)
        {
            setRegText(AppRegCost.RegJS);
        }

        private void cbDb_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbDb.SelectedItem == null || cbDb.SelectedItem.ToString() == "sqlsearcher.Models.TreeMapInfo")
                return;
            sqlCnSearch.CurrentDB = cbDb.SelectedValue.ToString();
            Task.Factory.StartNew(() =>
            {
                sqlCnSearch.Fill(TFac<SearchManager>.Instance.GetDataTableBySql(sqlCnSearch.CurrentDB, sqlCnSearch.GetTableDescSQL()));
            });
        }

        private void cbxTbs_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void button5_Click(object sender, EventArgs e)
        {

        }

        private void label10_Click(object sender, EventArgs e)
        {

        }

        private void 复制表名ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            try
            {
                if (tvView.SelectedNode.Level == 2)
                {
                    var value = tvView.SelectedNode.Text;
                    Clipboard.SetDataObject(value);

                }
            }
            catch (Exception)
            {

            }
        }

        private void 复制所有列名ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (tvView.SelectedNode.Level == 2)
                {
                    var value = tvView.SelectedNode.Text;

                    if (tvView.SelectedNode.Nodes.Count == 0)
                    {
                        var cns = TFac<SearchManager>.Instance.GetColumns(tvView.SelectedNode.Parent.Text, value);

                        if (cns.Item1)
                        {
                            data.Find(m => m.Node == tvView.SelectedNode.Parent.Text).Items.Find(m => m.Node == value).Items = cns.Item2;
                            TreeNode(cns.Item2, tvView.SelectedNode);
                        }
                    }
                    var viewData = TFac<SearchManager>.Instance.GetDetails(tvView.SelectedNode.Parent.Text, value);
                    if (viewData.Item1 > 0)
                    {
                        var str = new StringBuilder();
                        foreach (DataRow item in viewData.Item2.Rows)
                        {
                            str.AppendFormat("{0},", item["cName"].TryString());
                        }

                        Clipboard.SetDataObject(str.ToString().TrimEnd(','));
                    }

                }
            }
            catch (Exception)
            {

            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void lay_head_Click(object sender, EventArgs e)
        {
        }

        private void btnHttpSend_Click(object sender, EventArgs e)
        {
            var httpClient = new HttpClient();
            var httpEntity = new HttpEntity();
            try
            {
                this.txtResponseText.Text = string.Empty;
                httpEntity.HttpMethod = this.cbxHttpMethod.Text;
                httpEntity.HttpUrl = this.txtRequestUrl.Text;
                httpEntity.HttpContentType = EnumHelper.GetDescription<HttpContentType>((int)HttpContentType.Json);
                httpEntity.Data = this.txtRequestContent.Text;

                if (string.IsNullOrWhiteSpace(httpEntity.HttpMethod))
                    return;
                if (string.IsNullOrWhiteSpace(httpEntity.HttpUrl))
                    return;

                httpEntity.HttpResponseContent = httpClient.Send(httpEntity);
                httpEntity.HttpRequestTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                HttpSave.Write(httpEntity, httpEntity.HttpUrl);

                this.txtResponseText.Text = HttpClient.ConvertJsonString(httpEntity.HttpResponseContent).Result.Item2;
                this.tabHttp.SelectedIndex = 1;
                txtHttpHistory_TextChanged(null, null);
                TextColor.SetColor(this.txtResponseText);
                TextColor.SetColor(this.txtRequestContent);
            }
            catch (Exception ex)
            {
                this.txtResponseText.Text = httpEntity.HttpResponseContent;
            }
        }

        private void txtHttpHistory_TextChanged(object sender, EventArgs e)
        {
            LoadHistoryHttpRequest();
        }

        private void txtHttpHistory_MouseDown(object sender, MouseEventArgs e)
        {
            lbxHttpHistory.Visible = true;

        }

        private void lbxHttpHistory_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {

                lbxHttpHistory.Visible = false;

                var searchKey = lbxHttpHistory.Text;
                if (!string.IsNullOrWhiteSpace(searchKey))
                {
                    searchKey = searchKey.Replace(new Uri(searchKey).Host, "").Replace("http://", "").Replace("https://", "").Replace(":", "").Replace(new Uri(lbxHttpHistory.Text.ToLower()).Port.ToString(), "");
                    searchKey = searchKey.Replace("/", "_").TrimStart('_');
                }
                var httpformats = HttpSave.Reader<HttpEntityFormat>(searchKey);
                if (httpformats == null || httpformats.Count <= 0)
                    return;

                var httpEntityFormat = httpformats.First();
                this.cbxHttpMethod.SelectedItem = httpEntityFormat.HttpMethod;
                this.txtRequestUrl.Text = httpEntityFormat.HttpUrl;
                var responseContent = httpEntityFormat.HttpResponseContent.ToString();
                var requestContent = httpEntityFormat.Data.ToString();
                this.txtResponseText.Text = HttpClient.ConvertJsonString(responseContent).Result.Item2;
                this.txtRequestContent.Text = HttpClient.ConvertJsonString(requestContent).Result.Item2.ToString();
                TextColor.SetColor(this.txtResponseText);
                TextColor.SetColor(this.txtRequestContent);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "消息提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        private string SerializeObject(object value)
        {
            try
            {
                return JsonConvert.SerializeObject(value);
            }
            catch (Exception)
            {
                return value.ToString();
            }
        }

        private void LoadHistoryHttpRequest()
        {
            try
            {
                lbxHttpHistory.Visible = false;

                var httpformats = HttpSave.Reader<HttpEntityFormat>(txtHttpHistory.Text.Trim());
                if (httpformats == null || httpformats.Count <= 0)
                    return;

                lbxHttpHistory.Items.Clear();
                foreach (var item in httpformats)
                {
                    if (item == null)
                        continue;
                    if (!lbxHttpHistory.Items.Contains(item.HttpUrl))
                        lbxHttpHistory.Items.Add(item.HttpUrl);
                }
                lbxHttpHistory.Visible = true;
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "消息提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void jSON示例ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.txtRequestContent.Text = HttpClient.ConvertJsonString("{\"UserId\":\"\",\"Token\":\"\",\"FindId\":87}").Result.Item2;
        }

        private void 连接字符串示例ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.txtRequestContent.Text = "appkey=436436437&username=admin&num=2";
        }

        private void jSON格式化ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.txtRequestContent.Text = HttpClient.ConvertJsonString(this.txtRequestContent.Text).Result.Item2;
            TextColor.SetColor(this.txtRequestContent);
        }

        private void 查看历史请求ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(HttpSave.directoryPath);
        }





        private void txtRequestContent_TextChanged(object sender, EventArgs e)
        {
            txtRequestContent.BackColor = Color.White;
            var res = HttpClient.ConvertJsonString(txtRequestContent.Text).Result.Item1;
            if (!res)
            {
                txtRequestContent.BackColor = Color.Yellow;
            }
        }

        private void lbxHttpHistory_MouseMove(object sender, MouseEventArgs e)
        {
            lbxHttpHistory.Visible = true;
        }

        private void lbxHttpHistory_MouseLeave(object sender, EventArgs e)
        {
            lbxHttpHistory.Visible = false;
        }

        private void txtHttpHistory_MouseMove(object sender, MouseEventArgs e)
        {

        }

        private void txtRequestContent_MouseEnter(object sender, EventArgs e)
        {
            lbxHttpHistory.Visible = false;
        }

        private void txtHttpHistory_MouseEnter(object sender, EventArgs e)
        {
            LoadHistoryHttpRequest();
        }

        private void 清理历史ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.txtRequestContent.Text = string.Empty;
            this.txtResponseText.Text = string.Empty;
            this.txtRequestUrl.Text = string.Empty;
        }

        private void 清理历史ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("你确定要清除所有历史记录吗？") == DialogResult.OK)
            {
                HttpSave.Clear();
                MessageBox.Show("清理完成！", "消息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void txtSearchKey_TextChanged(object sender, EventArgs e)
        {
            try
            {
                var dt = new DataTable();
                dt.Columns.Add("词");
                dt.Columns.Add("描述");

                if (sqlCnSearch.serachKeywords == null || sqlCnSearch.serachKeywords.Count <= 0)
                {
                    var dr = dt.NewRow();
                    dr["词"] = "正在进行初始化,请稍后...";
                    dr["描述"] = "如仍未显示，请选择导航数据库";
                    dt.Rows.Add(dr);

                    dataGridView2.DataSource = dt;
                    dataGridView2.Columns[0].Width = 250;
                    dataGridView2.Columns[1].Width = 250;

                    tabControl3_SelectedIndexChanged(null, null);
                }
                if (string.IsNullOrWhiteSpace(txtSearchKey.Text.Trim()))
                    return;
                var res = sqlCnSearch.Search(txtSearchKey.Text.Trim());
                if (res != null)
                {

                    foreach (var item in res.Keys)
                    {
                        var dr = dt.NewRow();
                        dr["词"] = item;
                        dr["描述"] = res[item];
                        dt.Rows.Add(dr);
                    }
                    dataGridView2.DataSource = dt;
                    dataGridView2.Columns[0].Width = 250;
                    dataGridView2.Columns[1].Width = 250;
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void tabControl3_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (tabControl3.SelectedIndex == 1 && tvView.SelectedNode != null)
                {
                    if (tvView.SelectedNode.Level == 1)
                    {
                        if (tvView.SelectedNode.Text != sqlCnSearch.CurrentDB || sqlCnSearch.serachKeywords == null || sqlCnSearch.serachKeywords.Count <= 0)
                        {
                            sqlCnSearch.CurrentDB = tvView.SelectedNode.Text;
                            Task.Factory.StartNew(() =>
                            {
                                sqlCnSearch.Fill(TFac<SearchManager>.Instance.GetDataTableBySql(sqlCnSearch.CurrentDB, sqlCnSearch.GetTableDescSQL()));
                            });
                        }
                    }
                    else if (tvView.SelectedNode.Level == 2)
                    {
                        if (tvView.SelectedNode.Parent.Text != sqlCnSearch.CurrentDB || sqlCnSearch.serachKeywords == null || sqlCnSearch.serachKeywords.Count <= 0)
                        {
                            sqlCnSearch.CurrentDB = tvView.SelectedNode.Parent.Text;
                            Task.Factory.StartNew(() =>
                            {
                                sqlCnSearch.Fill(TFac<SearchManager>.Instance.GetDataTableBySql(sqlCnSearch.CurrentDB, sqlCnSearch.GetTableDescSQL()));
                            });
                        }
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            try
            {
                var txtQuery = GetSelectTagTextSQL();
                if (txtQuery == null)
                    return;

                if (cbDb.SelectedIndex == -1)
                {
                    txtQuery.Text.Insert(0, "需要指定数据库");
                }
                var dt = TFac<SearchManager>.Instance.GetTablesByDB(cbDb.Text);
                var dataCount = 0;
                var tabPage = new TabPage();
                var isAddTabPage = true;
                foreach (TabPage item in tabSqlResult.TabPages)
                {
                    if (item.Text == "表清单的结果")
                    {
                        tabPage = item;
                        isAddTabPage = false;
                    }
                }
                tabPage.Text = "表清单的结果";
                tabPage.Controls.Clear();

                var gridView = getNewGridView();
                gridView.DataSource = dt;

                tabPage.Controls.Add(gridView);

                if (isAddTabPage)
                {
                    tabSqlResult.TabPages.Add(tabPage);
                }
                dataCount += dt.Rows.Count;

                if (dataCount == 0)
                {
                    txtSqlResult.Text = "没有查到任何数据";
                }
                else
                {
                    txtSqlResult.Text = $"一共查到：{dataCount}行数据";
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void btnExec_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txtCode.Text))
                    return;
                exResult.Text = Evaluator.Eval(txtCode.Text).ToString();//DynamicExec.Run(txtCode.Text);
            }
            catch (Exception ex)
            {
                exResult.Text = ex.StackTrace;
            }
        }

        private void btnAddSingleChar_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txtCode.Text))
                    return;
                if (txtCode.Text.IndexOf("\n") != -1)
                    txtCode.Text = txtCode.Text.Replace("\n", ",").Replace("\r", "");

            }
            catch (Exception)
            {
            }
        }

        private void btnRanName_Click(object sender, EventArgs e)
        {
            try
            {
                var nameData = MyValueData.GetNames();
                exResult.Text = nameData[new Random().Next(0, nameData.Length - 1)].Replace(" ", "").Trim();
            }
            catch (Exception)
            {

            }
        }

        private void btnNick_Click(object sender, EventArgs e)
        {
            try
            {
                var nickData = MyValueData.GetNicks();
                exResult.Text = nickData[new Random().Next(0, nickData.Length - 1)].Replace(" ", "").Trim();
            }
            catch (Exception)
            {

            }
        }

        private void btnProductName_Click(object sender, EventArgs e)
        {
            try
            {
                var nickData = MyValueData.productNames();
                exResult.Text = nickData[new Random().Next(0, nickData.Length - 1)].Replace(" ", "").Trim();
            }
            catch (Exception)
            {

            }
        }

        private void btnVen_Click(object sender, EventArgs e)
        {
            try
            {
                var nickData = MyValueData.venNames();
                exResult.Text = nickData[new Random().Next(0, nickData.Length - 1)].Replace(" ", "").Trim();
            }
            catch (Exception)
            {

            }
        }

        private void btnExitLogin_Click(object sender, EventArgs e)
        {
            TFac<MenuFm>.Instance.Hide();
            TFac<Login>.Instance.Show();

        }

        private void btnVersion_Click(object sender, EventArgs e)
        {
            var path = Application.StartupPath;
            if (File.Exists(AppConst.versionPath))
                txtCode.Text = new StreamReader(AppConst.versionPath).ReadToEnd();
        }

        private void MenuFm_Load(object sender, EventArgs e)
        {
            ReLoad();
        }



        private void txtSql_TextChanged(object sender, EventArgs e)
        {
            var txtQuery = GetSelectTagTextSQL();
            if (txtQuery == null)
                return;
            this.build(txtQuery);
        }

        private void build(RichTextBox txtQuery)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txtQuery.Text))
                    return;

                //  获得txtSql最后一个空格到结尾的位置
                var getStringStartIndex = 0;
                if (txtQuery.Text.LastIndexOf(" ") != -1)
                {
                    getStringStartIndex = txtQuery.Text.LastIndexOf(" ");
                }
                var getStringLength = txtQuery.Text.Length - getStringStartIndex;
                var getString = txtQuery.Text.Substring(getStringStartIndex, getStringLength).Replace(" ", "");

                var dt = new DataTable();
                dt.Columns.Add("词");
                var keywords = new List<string>() { getString };
                foreach (var item in TFac<SqlServerKeyWords>.Instance.GetKeys())
                {
                    if (item.ToLower().IndexOf(getString.ToLower()) != -1)
                    {
                        keywords.Add(item);
                    }
                }
                if (sqlCnSearch.serachKeywords == null || sqlCnSearch.serachKeywords.Count <= 0)
                {
                    if (cbDb.SelectedItem != null)
                    {
                        sqlCnSearch.CurrentDB = cbDb.SelectedValue.ToString();
                        Task.Factory.StartNew(() =>
                        {
                            var descSQL = sqlCnSearch.GetTableDescSQL();
                            var descData = TFac<SearchManager>.Instance.GetDataTableBySql(sqlCnSearch.CurrentDB, descSQL);
                            sqlCnSearch.Fill(descData);
                        });
                    }
                    return;
                }
                foreach (var item in sqlCnSearch.serachKeywords)
                {
                    if (item.Key.ToLower().IndexOf(getString.ToLower()) != -1)
                    {
                        keywords.Add(item.Key);
                    }
                }
                foreach (var item in keywords.Distinct())
                {
                    var dr = dt.NewRow();
                    dr["词"] = item;
                    dt.Rows.Add(dr);
                }
                dataGridViewSqlSearch.DataSource = dt;

            }
            catch (Exception ex)
            {

            }
        }
        Timer timer = new Timer();
        private void dataGridViewSqlSearch_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (dataGridViewSqlSearch.SelectedCells.Count <= 0)
                    return;
                var str = dataGridViewSqlSearch.SelectedCells[0].Value.ToString();
                if (string.IsNullOrWhiteSpace(str))
                    return;
                var txtQuery = GetSelectTagTextSQL();
                if (txtQuery == null)
                    return;
                if (string.IsNullOrWhiteSpace(txtQuery.Text))
                    return;

                txtQuery.Text = txtQuery.Text + " ";

                var sourceIndex = 0;
                var endIndex = txtQuery.Text.LastIndexOf(" ");
                var newChar = str;

                var oldStr = txtQuery.Text.Substring(sourceIndex, endIndex);
                oldStr = oldStr.Substring(0, oldStr.LastIndexOf(" ")-"".Length);

                var newStr = oldStr +" "+ newChar;
                txtQuery.Text = newStr;


                timer.Interval = 20;
                timer.Tick += (a, b) =>
                {
                    txtQuery.Text = newStr;
                    txtQuery.SelectionStart = txtQuery.Text.Length;
                    UpdateQuerySQLStyle(null, null);
                    timer.Stop();
                };
                timer.Enabled = true;
                timer.Start();
            }
            catch (Exception ex)
            {

            }
        }
        private RichTextBox GetSelectTagTextSQL()
        {
            RichTextBox txtQuery = null;
            foreach (var item in tabSQLQuery.SelectedTab.Controls)
            {
                if (item is RichTextBox)
                {
                    txtQuery = item as RichTextBox;
                }
            }
            return txtQuery;
        }

        private static List<string> keys = null;
        private void UpdateQuerySQLStyle(object sender, EventArgs e)
        {
            var txtQuery = GetSelectTagTextSQL();
            if (txtQuery == null)
                return;
            if (string.IsNullOrWhiteSpace(txtQuery.Text))
                return;
            if (keys == null)
            {
                keys = sqlCnSearch.serachKeywords.Select(m => m.Key).ToList();
            }
            //SqlTextColor.SetColor(txtQuery, TFac<SqlServerKeyWords>.Instance.GetKeys(), keys);
        }

        /// <summary>
        /// 获取计算机信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exToolsSysInfo_Click(object sender, EventArgs e)
        {
            var sb = new StringBuilder();
            sb.AppendLine($"计算机名称:\t{TFac<SystemInfo>.Instance.GetMyComputerName()}");
            sb.AppendLine($"操作系统:\t{TFac<SystemInfo>.Instance.GetMyOSName()}");
            sb.AppendLine($"用户名:\t{TFac<SystemInfo>.Instance.GetMyUserName()}");
            sb.AppendLine($"驱动器大小:\t{TFac<SystemInfo>.Instance.GetMyDriveInfo()}");
            sb.AppendLine($"内存:\t{TFac<SystemInfo>.Instance.GetMyMemoryInfo()}");
            sb.AppendLine($"显卡:\t{TFac<SystemInfo>.Instance.GetMyScreens()}");
            sb.AppendLine($"CPU:\t{TFac<SystemInfo>.Instance.GetMyCpuInfo()}");
            sb.AppendLine($"局域网IP:\t{string.Join(",", TFac<SystemInfo>.Instance.GetLocalIpAddress("InterNetwork"))}");
            exResult.Text = sb.ToString();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("mstsc");
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("regedt32.exe");
        }

        private void exToolsByWinService_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("services.msc");

        }
        /// <summary>
        /// 打开系统属性
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exToolsBySystem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("rundll32.exe", "shell32.dll,Control_RunDLL sysdm.cpl");
        }
        public TabPage FindTabPageForm(string name)
        {
            foreach (TabPage tp in tabControl1.TabPages)
            {
                if (name == tp.Name)
                {
                    return tp;
                }
            }
            return null;
        }










        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exToolsByTime_Click(object sender, EventArgs e)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
            long timeStamp = (long)(DateTime.Now - startTime).TotalMilliseconds; // 相差毫秒数
            exResult.Text = timeStamp.ToString();
        }

        /// <summary>
        /// 获取IP地址
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exToolsByIPAddress_Click(object sender, EventArgs e)
        {
            var ips = new List<string>();
            string name = Dns.GetHostName();
            IPAddress[] ipadrlist = Dns.GetHostAddresses(name);
            foreach (IPAddress ipa in ipadrlist)
            {
                if (ipa.AddressFamily == AddressFamily.InterNetwork)
                    ips.Add(ipa.ToString());
            }
            if (ips == null || ips.Count <= 0)
            {
                exResult.Text = "127.0.0.1";
                return;
            }

            exResult.Text = string.Join("\r\n", ips);
        }



        /// <summary>
        /// 打开cmd
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exToolsByCmd_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("cmd.exe");
        }

        private void loadSql(string sqlFile)
        {
            var path = Application.StartupPath + "\\sql\\" + sqlFile + ".sql";
            if (File.Exists(path))
                exResult.Text = new StreamReader(path).ReadToEnd();
        }

        /// <summary>
        /// 递归根查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exToolsByTreeQParent_Click(object sender, EventArgs e)
        {
            loadSql(EnumHelper.GetDescription<AppEnum.SQLEnum>((int)AppEnum.SQLEnum.TreeQueryParent));
        }

        /// <summary>
        /// 递归子查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exToolsByTreeQChilds_Click(object sender, EventArgs e)
        {
            loadSql(EnumHelper.GetDescription<AppEnum.SQLEnum>((int)AppEnum.SQLEnum.TreeQueryChilds));
        }

        /// <summary>
        /// 列转行查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exToolsByColumnToRow_Click(object sender, EventArgs e)
        {
            loadSql(EnumHelper.GetDescription<AppEnum.SQLEnum>((int)AppEnum.SQLEnum.ColumnConvertRow));
        }

        /// <summary>
        /// 建索引
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exToolsByIndex_Click(object sender, EventArgs e)
        {
            loadSql(EnumHelper.GetDescription<AppEnum.SQLEnum>((int)AppEnum.SQLEnum.CreateIndex));
        }

        private void exToolsByTempTable_Click(object sender, EventArgs e)
        {
            loadSql(EnumHelper.GetDescription<AppEnum.SQLEnum>((int)AppEnum.SQLEnum.CreateTempTable));
        }

        private void exToolsByMutileRowInsert_Click(object sender, EventArgs e)
        {
            loadSql(EnumHelper.GetDescription<AppEnum.SQLEnum>((int)AppEnum.SQLEnum.MutileInsert));
        }

        private void exToolsByNorepeat_Click(object sender, EventArgs e)
        {
            loadSql(EnumHelper.GetDescription<AppEnum.SQLEnum>((int)AppEnum.SQLEnum.Dist));
        }

        private void exToolsByGroupSort_Click(object sender, EventArgs e)
        {
            loadSql(EnumHelper.GetDescription<AppEnum.SQLEnum>((int)AppEnum.SQLEnum.GroupSort));
        }

        private void exToolsByLock_Click(object sender, EventArgs e)
        {
            loadSql(EnumHelper.GetDescription<AppEnum.SQLEnum>((int)AppEnum.SQLEnum.Lock));
        }

        private void exToolsByVersion_Click(object sender, EventArgs e)
        {
            var path = Application.StartupPath;
            if (File.Exists(AppConst.versionPath))
                exResult.Text = new StreamReader(AppConst.versionPath).ReadToEnd();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            exResult.Text = @"EXECUTE sp_addextendedproperty N'MS_Description', N'商品表', N'USER', N'dbo',
     N'table', N'product';";
        }


        private TextBox getNewTextBox()
        {
            var txtbox = new TextBox();
            txtbox.Dock = System.Windows.Forms.DockStyle.Fill;
            txtbox.Location = new System.Drawing.Point(4, 4);
            txtbox.Margin = new System.Windows.Forms.Padding(4);
            txtbox.Name = "txt" + new Random().Next(1000, 9999);
            txtbox.Size = new System.Drawing.Size(1280, 254);
            txtbox.TabIndex = 0;
            txtbox.Text = "";
            return txtbox;
        }

        private RichTextBox getNewRTextBox()
        {
            var rtxt = new RichTextBox();
            rtxt.AcceptsTab = true;
            rtxt.AutoWordSelection = true;
            rtxt.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
            rtxt.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            rtxt.BulletIndent = 4;
            rtxt.EnableAutoDragDrop = true;
            rtxt.Font = new System.Drawing.Font("新宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            rtxt.Location = new System.Drawing.Point(32, 13);
            rtxt.Margin = new System.Windows.Forms.Padding(4);
            rtxt.Name = "rtxt" + new Random().Next(1000, 9999);
            rtxt.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.ForcedBoth;
            rtxt.ShowSelectionMargin = true;
            rtxt.Size = new System.Drawing.Size(299, 120);
            rtxt.TabIndex = 0;
            rtxt.Text = "";
            rtxt.Dock = DockStyle.Fill;
            rtxt.TextChanged += (a, b) =>
            {
                build(rtxt);
            };
            rtxt.PreviewKeyDown += txtSql_PreviewKeyDown;
            return rtxt;
        }

        private void button5_Click_1(object sender, EventArgs e)
        {

            if (tabSQLQuery.SelectedTab == null)
                return;
            foreach (var item in tabSQLQuery.SelectedTab.Controls)
            {
                if (item is RichTextBox)
                {
                    BuildUpdate(tabSQLQuery.SelectedTab, item as RichTextBox);
                }
            }
        }

        private void BuildUpdate(TabPage queryTab, RichTextBox txtQuery)
        {
            try
            {
                string execSQL = txtQuery.Text;
                if (string.IsNullOrWhiteSpace(txtQuery.SelectedText) && string.IsNullOrWhiteSpace(txtQuery.Text))
                    return;

                if (cbDb.SelectedIndex == -1)
                {
                    txtQuery.Text.Insert(0, "需要指定数据库");
                    return;
                }

                if (!string.IsNullOrWhiteSpace(txtQuery.SelectedText))
                    execSQL = txtQuery.SelectedText;

                var count = SearchManager.dbUtils.Cmd(cbDb.Text, execSQL);
                txtSqlResult.Text = "受影响行数：" + count;
                tabControl2.SelectedIndex = 1;
            }
            catch (Exception ex)
            {
                txtSqlResult.Text = ex.Message;
            }
        }

        private void btnAddQuery_Click(object sender, EventArgs e)
        {
            var count = tabSQLQuery.Controls.Count;

            var tabPage = new TabPage();
            tabPage.Text = "查询窗口" + (count + 1);

            var textBox = getNewRTextBox();
            tabPage.Controls.Add(textBox);

            tabSQLQuery.Controls.Add(tabPage);
            tabSQLQuery.SelectedTab = tabPage;
        }

        private void tsDelTagPage_Click(object sender, EventArgs e)
        {
            if (tabSQLQuery.SelectedTab == null)
                return;
            List<TabPage> removeResultTab = new List<TabPage>();
            foreach (TabPage item in tabSqlResult.TabPages)
            {
                if ( item.Text.IndexOf((tabSQLQuery.SelectedTab.Text + "的结果")) !=-1)
                {
                    removeResultTab .Add( item);
                }
            }
            if (removeResultTab != null&&removeResultTab.Count>0)
            {
                foreach (var item in removeResultTab)
                {
                    tabSqlResult.TabPages.Remove(item);
                }
            }
                
            tabSQLQuery.TabPages.Remove(tabSQLQuery.SelectedTab);
        }

        private void tsAddQueryHeight_Click(object sender, EventArgs e)
        {
            panel3.Height = panel3.Height + 50;
            if (panel3.Height > 600)
            {
                panel3.Height = 600;
            }
        }

        private void tsReduceQueryHeight_Click(object sender, EventArgs e)
        {
            panel3.Height = panel3.Height - 50;
            if (panel3.Height < 100)
            {
                panel3.Height = 100;
            }
        }

        private void tsSaveQuerySQL_Click(object sender, EventArgs e)
        {
            if (tabSQLQuery.SelectedTab == null)
                return;
            saveFileDialog1.FileName = tabSQLQuery.SelectedTab.Text;
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                var path = saveFileDialog1.FileName;
                using (StreamWriter sw = new StreamWriter(path))
                {
                    foreach (var item in tabSQLQuery.SelectedTab.Controls)
                    {
                        if (item is RichTextBox)
                        {
                            if (string.IsNullOrWhiteSpace((item as RichTextBox).Text))
                            {
                                MessageBox.Show("保存内容不能为空！", "消息提示", MessageBoxButtons.OK);
                                return;
                            }
                            sw.Write((item as RichTextBox).Text);
                        }
                    }

                }
            }
        }

        private void txtSql_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.Up)
            {
                try
                {
                    var selectIndex = 0;
                    var index = 0;
                    foreach (DataGridViewRow item in dataGridViewSqlSearch.Rows)
                    {
                        if (item.Selected)
                        {
                            selectIndex = index;
                            break;
                        }
                        index++;
                    }
                     index = 0;
                    foreach (DataGridViewRow item in dataGridViewSqlSearch.Rows)
                    {
                        if (selectIndex - 1 == 0 || selectIndex - 1 < 0)
                        {
                            dataGridViewSqlSearch.Rows[0].Selected = true;
                            break;
                        }
                        if (index == selectIndex - 1)
                        {
                            item.Selected = true;
                            item.Cells[0].Selected = true;
                            break;
                        }
                        else
                        {
                            item.Selected = false;
                        }
                        index++;
                    }
                }
                catch (Exception ex)
                {

                }
            }

            if (e.KeyCode == Keys.Down)
            {
                try
                {
                    var selectIndex = 0;
                    var index = 0;
                    foreach (DataGridViewRow item in dataGridViewSqlSearch.Rows)
                    {
                        if (item.Selected)
                        {
                            selectIndex = index;
                            break;
                        }
                        index++;
                    }

                    index = 0;
                    foreach (DataGridViewRow item in dataGridViewSqlSearch.Rows)
                    {
                        if (index == selectIndex + 1)
                        {
                            item.Selected = true;
                            item.Cells[0].Selected = true;
                            break;
                        }
                        else
                        {
                            item.Selected = false;
                        }
                        index++;
                    }
                }
                catch (Exception ex)
                {

                }
            }
            if (e.KeyCode == Keys.Enter)
            {
                if (dataGridViewSqlSearch.SelectedRows.Count > 0)
                {
                    dataGridViewSqlSearch_CellClick(null, null);
                }
            }
        }

        private void txToolsByJsonModel_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txtCode.Text.Trim()))
                    return;

                exResult.Text = JsonToModel.ToModel(txtCode.Text.Trim());
            }
            catch 
            {
                exResult.Text = "转换失败，请检查格式";
            }
        }

        private void exToolsByJsonFormat_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txtCode.Text.Trim()))
                return;
            txtCode.Text = HttpClient.ConvertJsonString(txtCode.Text.Trim()).Result.Item2;
            }
            catch
            {
                exResult.Text = "转换失败，请检查格式";
            }
        }

        private void button5_Click_2(object sender, EventArgs e)
        {
            TFac<NameFrm>.Instance.StartPosition = FormStartPosition.CenterParent;
            TFac<NameFrm>.Instance.backSource = AppConst.source_bianqian;
            TFac<NameFrm>.Instance.ShowDialog();


        }

        private void panel30_Paint(object sender, PaintEventArgs e)
        {

        }

        private void 删除便签ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lvPList.SelectedItems.Count <= 0)
                return;
            if (MessageBox.Show("你确定要删除“"+lvPList.SelectedItems[0].Text+"”吗") != DialogResult.OK)
                return;

            TFac<BianQianData>.Instance.Delete(lvPList);
        }

        private void lvPList_SelectedIndexChanged(object sender, EventArgs e)
        {
            rtxtBianQian.Text = TFac<BianQianData>.Instance.Get(lvPList);
        }

        private void rtxtBianQian_TextChanged(object sender, EventArgs e)
        {
            TFac<BianQianData>.Instance.Update(lvPList, rtxtBianQian.Text);
        }
    }
}
